//
//  SEPrescriptionPickDiagnosisListView.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/5/11.
//

import UIKit

class SEPrescriptionPickDiagnosisListView: UIView {

    var viewModel = SEPrescriptionDiagnosisPickViewModel() {
        didSet {
            searchBar.isHidden = viewModel.type != .diagnose
            activityIndicator.isHidden = viewModel.type == .diagnose
            titleLabel.isHidden = viewModel.type == .diagnose
            switch viewModel.type {
            case .prefix:
                titleLabel.text = "前缀"
                loadPrefixAndSuffix(mark: "diagnose_pre")
            case .suffix:
                titleLabel.text = "后缀"
                loadPrefixAndSuffix(mark: "diagnose_suf")
            case .diagnose:
                setupRefresh()
            }

            bindViewModel()
        }
    }
    
    var selectedHandler: ((SEPrescriptionDiagnosisPickViewModel) -> Void)?
    var dismissHandler: (() -> Void)?
    
    private func bindViewModel() {
        viewModel.updateData = { [weak self] httpStatus in
            if self?.viewModel.type != .diagnose {
                self?.activityIndicator.stopAnimating()
            } else {
                self?.endRefreshing()
            }
            self?.tableView.reloadData()
        }
    }
    
    private func loadPrefixAndSuffix(mark: String) {
        activityIndicator.startAnimating()
        viewModel.getListOfDiagnosisPrefixAndSuffix(mark: mark)
    }
    
    private func loadData(_ more: Bool = false) {
        viewModel.getListOfDiagnosisResult(more)
        viewModel.updateData = { [weak self] status in
            self?.endRefreshing()
            self?.tableView.reloadData()
        }
    }
    
    private func setupRefresh() {
        let header = SERefreshHeader { [weak self] in self?.loadData() }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        tableView.se_header = header
        tableView.se_footer = SERefreshFooter { [weak self] in self?.loadData(true) }
        tableView.se_header?.beginRefreshing()
    }
    
    @IBOutlet private weak var titleLabel: UILabel!
    
    @IBOutlet private weak var activityIndicator: UIActivityIndicatorView!

    @IBOutlet private weak var searchBar: UISearchBar! {
        didSet { searchBar.delegate = self }
    }

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .white
            tableView.tableFooterView = UIView()
            tableView.delegate = self
            tableView.dataSource = self

            tableView.register(SEPrescriptionPickDiagnosisListCell.nibForCell(),
                               forCellReuseIdentifier: SEPrescriptionPickDiagnosisListCell.reuseIdentifier())
        }
    }
    
    @IBAction private func dismissAction() {
        searchBar.resignFirstResponder()
        dismissHandler?()
    }
    
    func endRefreshing() {
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }
}

extension SEPrescriptionPickDiagnosisListView: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionPickDiagnosisListCell.reuseIdentifier(),
                                                 for: indexPath) as! SEPrescriptionPickDiagnosisListCell
        cell.update(with: viewModel.viewModel(at: indexPath))
        return cell
    }
}

extension SEPrescriptionPickDiagnosisListView: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vm = viewModel.viewModel(at: indexPath)
        selectedHandler?(vm)
        dismissHandler?()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.cellHeight
    }
}

extension SEPrescriptionPickDiagnosisListView: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        viewModel.content = searchBar.text ?? ""
        tableView.se_header?.beginRefreshing()
    }
}
